
import cv2
import pytesseract
import numpy as np
from PIL import Image

'''
处理二维码识别能力
'''
# 显式指定Tesseract路径(根据实际安装位置调整)
pytesseract.pytesseract_cmd =  r'D:\tesseract\tesseract.exe'
pytesseract.pytesseract.tesseract_cmd =  r'D:\tesseract\tesseract.exe'

#验证码识别配置
config='--psm 8 --oem 3 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'
#中文识别配置
# config='--psm 1 --oem 3 -l chi_sim'

class CaptchaRecognizer:
    def __init__(self, tesseract_cmd=None):
        if tesseract_cmd:
            pytesseract.pytesseract.tesseract_cmd = tesseract_cmd
    def preprocess_image(self, image_path):
        """图像预处理流程"""
        # 读取图像
        img = cv2.imread(image_path)
        
        # 1. 去噪
        img = cv2.bilateralFilter(img, 9, 75, 75)
        
        # 2. 灰度化
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        
        # 3. 自适应阈值二值化
        thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                     cv2.THRESH_BINARY_INV, 11, 2)
        
        # 4. 形态学操作
        kernel = np.ones((3,3), np.uint8)
        processed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
        
        return processed
    
    def recognize(self, image_path, preprocess=True):
        """识别验证码"""
        if preprocess:
            image = self.preprocess_image(image_path)
        else:
            image = Image.open(image_path)
        
        # 执行OCR
        text = pytesseract.image_to_string(image, config=config)
        
        return text

if __name__ == '__main__':
    recognizer = CaptchaRecognizer()
    result1 = recognizer.recognize(r'E:\project\py\studly\img\image.png',False)
    print(f"验证码识别结果: {result1}")
